﻿using AutoMapper;
using ManagementApi.Authorizers;
using ManagementApi.Models;
using ManagementApi.Mvc;
using ManagementApi.Mvc.ApplicationContexts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Modules;
using Modules.Commander;
using Modules.Project;
using PmSoft.Exceptions;

namespace ManagementApi.Controllers.CommanderPannel
{
    [Route("/api/v1/commander/common")]
    [ApiController]
    [Authorize(Roles = "Commander")]
    public class CommonController : ControllerBase
    {
        private readonly CommanderService commanderService;
        private readonly ProjectGroupService projectGroupService;
        private readonly ProjectCommanderApplicationContext applicationContext;
        private readonly CommanderProjectService commanderProjectService;
        private readonly IMapper mapper;

        /// <summary>
        /// </summary>
        /// <param name="commanderService"></param>
        /// <param name="projectGroupService"></param>
        /// <param name="applicationContext"></param>
        /// <param name="mapper"></param>
        /// <param name="commanderProjectService"></param>
        public CommonController(CommanderService commanderService, ProjectGroupService projectGroupService, ProjectCommanderApplicationContext applicationContext, IMapper mapper, CommanderProjectService commanderProjectService)
        {
            this.commanderService = commanderService;
            this.applicationContext = applicationContext;
            this.projectGroupService = projectGroupService;
            this.mapper = mapper;
            this.commanderProjectService = commanderProjectService;
        }

        /// <summary>
        /// 切换项目
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        [HttpPut("projectChanges/{projectId}")]
        public ApiResult ProjectChanges(int projectId)
        {
            #region 验证数据权限

            if (applicationContext.CurrentUser == null) throw new BusinessException("登录信息不存在");
            if (!commanderProjectService.ExistsCommanderProject(projectId, applicationContext.CurrentUser.Id)) throw new OwnAuthorizationFailedException();

            #endregion 验证数据权限

            if (applicationContext.CurrentUser == null) return ApiResult.Failure("系统异常,请重新登陆");
            CommanderInfo? commanderInfo = commanderService.GetCommanderInfo(applicationContext.CurrentUser.Id);
            if (commanderInfo == null)
                return ApiResult.Failure("指挥部信息不存在");
            commanderService.UpdateDefaultProjectId(commanderInfo, projectId);
            return ApiResult.Success("项目切换成功");
        }
    }
}